<template>
  <div class="dynamic-bg">
    <canvas ref="canvas"></canvas>
  </div>
</template>

<script>
export default {
  name: "PostListBG",
  mounted() {
    this.initCanvas();
  },
  beforeUnmount() {
    window.removeEventListener("resize", this.resizeHandler); // 添加卸载事件
  },
  methods: {
    initCanvas() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");
      let particles = [];

      // 动态调整画布尺寸（提取为方法便于卸载）
      this.resizeHandler = () => {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
      };
      window.addEventListener("resize", this.resizeHandler);
      this.resizeHandler();

      // 改用浅色系颜色
      const colors = [
        "#6dd5edff", // 浅天蓝
        "#64ffdaff", // 薄荷绿
        "#ff80ab80", // 浅品红
        "#ff9966aa", // 浅珊瑚色
        "#ffd70060", // 浅金色
        "#e5737360", // 浅砖红色
        "#ba68c860", // 浅紫藤色
      ];

      class Particle {
        constructor() {
          this.reset();
        }
        reset() {
          this.x = Math.random() * canvas.width;
          this.y = Math.random() * canvas.height;
          this.radius = Math.random() * 8 + 1; // 增大粒子尺寸
          this.color = colors[Math.floor(Math.random() * colors.length)];
          this.velocity = {
            x: (Math.random() - 0.5) * 0.8, // 加快运动速度
            y: (Math.random() - 0.5) * 0.8,
          };
        }
        draw() {
          ctx.beginPath();
          ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
          ctx.fillStyle = this.color;
          ctx.fill();
        }
        update() {
          this.x += this.velocity.x;
          this.y += this.velocity.y;
          if (this.x < 0 || this.x > canvas.width) this.velocity.x *= -1;
          if (this.y < 0 || this.y > canvas.height) this.velocity.y *= -1;
          this.draw();
        }
      }

      // 增加粒子数量提升效果
      for (let i = 0; i < 200; i++) {
        particles.push(new Particle());
      }

      // 添加鼠标互动（增强视觉效果）
      canvas.addEventListener("mousemove", (e) => {
        particles.forEach((p) => {
          const dx = e.clientX - p.x;
          const dy = e.clientY - p.y;
          p.velocity.x += dx * 0.0005;
          p.velocity.y += dy * 0.0005;
        });
      });

      // 动画循环
      const animate = () => {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        particles.forEach((p) => p.update());
        requestAnimationFrame(animate);
      };
      animate();
    },
  },
};
</script>

<style scoped>
.dynamic-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: -1; /* 修改层级关系 */
  background: linear-gradient(120deg, #694a13 0%, #2d1179 100%); /* 浅色渐变 */
  overflow: hidden;
}

canvas {
  opacity: 0.9;
  mix-blend-mode: soft-light; /* 更柔和的混合模式 */
}
</style>